<script setup lang="jsx">
import {computed, inject, ref, watch} from "vue";
import DataGrid from "@cps/DataGrid/DataGrid.vue";
import {Message} from "@arco-design/web-vue";
import parcel from "@/api/document/parcel.js";
import declareColumns from "@/utils/shipmentTools.js";

const record = inject('record')
const crudRef = inject('crudRef')
const getRecord = inject('getRecord')
const visible = defineModel()
const originalData = inject('parcelData', [])
const userData = ref([])
const form = ref({
  later:false,
  count:0,
})
const originalColumns = inject('originalDeclareColumns');
const maxNumber = computed(()=> Number(originalData.value.map(i=>i.number).sort().reverse()[0]?.match(/\d+$/)[0] ?? 0))
const columns = computed(function(){return declareColumns.formatDeclareColumns(originalColumns.value,'add').filter(i=>form.value.later ? !i.isDeclare : true)})

watch(visible,async (value) => {
  if(value){
    return
  }
  form.value = {later:false, count:0,}
})
const countChanged = (v)=>{
  userData.value.length = 0
  for (let i = 0; i < v + 5; i++) {
    let data = {}
    data.ext_number = data.number = i < v ? (maxNumber.value + i + 1) : ''
    userData.value[i] = data
  }
  userData.value.length = v + 5
  // console.log(userData.value)
}
const submit = async () => {
  userData.value = userData.value.filter(i=> ![undefined,null,''].includes(i.ext_number))
  userData.value.map(i=>{
    i.ext_number = i.number
  })
  let res = await parcel.save({
    shipment_id:record.value.id,
    parcel:userData.value,
    parcel_count:form.value.count,
    declare_later:form.value.later,
  })
  if(!res.success){
    Message.error(res.message)
    return false;
  }
  Message.info(res.message)
  visible.value = false
  form.value.count = 0
  getRecord()
  // crudRef.value.refresh()
  return false;
}
</script>

<template>
  <a-drawer
      :visible="visible"
      title="添加货箱"
      width="70%"
      :destroyOnClose="true"
      :getContainer="false"
      :style="{position: 'absolute'}"
      @cancel="visible = false"
      @ok="submit"
  >
    <a-space class="grid align-center justify-center">
      <a-form-item label="添加数量" required>
        <a-input-number v-model="form.count" @change="countChanged" :min="0"/>
      </a-form-item>
      <a-form-item label="申报后补">
        <a-checkbox v-model="form.later" />
      </a-form-item>
    </a-space>
    <a-row>
      <a-col>
      </a-col>
    </a-row>
    <data-grid :columns="columns" v-model="userData" v-if="form.count"/>
  </a-drawer>
</template>

<style scoped>

</style>